
var localVideo = document.querySelector('video#localvideo');
var remoteVideo = document.querySelector('video#remotevideo');
var btnStart = document.querySelector('button#start');
var btnCall = document.querySelector('button#call');
var btnHangUp = document.querySelector('button#hangup');

var localStream;
var pc1;
var pc2;


function getMediaStream(stream){
	localVideo.srcObject = stream;
	localStream = stream;
}

function handleError(err){
	console.error("获取用户设备失败");
}

function start(){
	if(!navigator.mediaDevices
		|| !navigator.mediaDevices.getUserMedia){
		console.error("不支持");
	}else{
		var constraints = {
			video:true,
			audio:false
		}
		navigator.mediaDevices.getUserMedia(constraints)
				.then(getMediaStream)
				.catch(handleError)
	}
}


function call(){
	pc1 = new RTCPeerConnection();
	pc2 = new RTCPeerConnection();
	//收到候选者
	pc1.onicecandidate = (event)=>{
		//将新接收到的候选者传递给浏览器的ICE代理
		pc2.addIceCandidate(event.candidate);
	}
	
	pc2.onicecandidate = (event)=>{
		pc1.addIceCandidate(event.candidate);
	};
	
	//当关联到媒体轨时，展示到remoteVideo中
	pc2.ontrack = (event)=>{
		remoteVideo.srcObject = event.streams[0];
	};
	
	localStream.getTracks().forEach((track)=>{
		//添加媒体轨
		pc1.addTrack(track,localStream);
	});
	var offerOptions = {
		offerToRecieveAudio:0,
		offerToRecieveVideo:1
	};
	//启动一个新的WebRTC去连接远程端点
	pc1.createOffer(offerOptions)
		.then((desc)=>{
			//设置本地Description
			pc1.setLocalDescription(desc);
			//设置远端Description（正常应该通过服务器发送给远端）
			pc2.setRemoteDescription(desc);
			//创建远程端点的应答信息
			pc2.createAnswer().then((desc2)=>{
				//设置本地Description
				pc2.setLocalDescription(desc2);
				//设置远端Description（正常应该通过服务器发送给远端）
				pc1.setRemoteDescription(desc2);
			}).catch((e)=>{
				console.error(e);
			});
		})
		.catch();
}

function hangUp(){
	pc1.close();
	pc2.close();
	pc1 = null;
	pc2 = null;
}

btnStart.onclick = start;
btnCall.onclick = call;
btnHangUp.onclick = hangUp;

